<template>
  <view class="book-detail-container">
    <!-- 书籍封面展示区 -->
    <view class="book-cover-section">
      <view class="book-cover-circle">
        <image :src="url('b', book.img, 'png')" class="book-cover" mode="aspectFill"></image>
      </view>
      <view class="book-title">  《{{ book.title }}》</view>
    </view>

    <!-- 书籍详情信息 -->
    <view class="book-info-section">
      <view class="info-table">
        <view class="info-row" v-if="book.detail.type">
          <view class="info-label">作品类型</view>
          <view class="info-value">{{ book.detail.type }}</view>
        </view>
        <view class="info-row" v-if="book.detail.author">
          <view class="info-label">作 者</view>
          <view class="info-value">{{ book.detail.author }}</view>
        </view>
        <view class="info-row" v-if="book.detail.time">
          <view class="info-label">成书时间</view>
          <view class="info-value">{{ book.detail.time }}</view>
        </view>
        <view class="info-row" v-if="book.detail.volume">
          <view class="info-label">卷 数</view>
          <view class="info-value">{{ book.detail.volume }}</view>
        </view>
        <view class="info-row" v-if="book.detail.pages">
          <view class="info-label">页 数</view>
          <view class="info-value">{{ book.detail.pages }}</view>
        </view>
        <view class="info-row" v-if="book.detail.publishTime">
          <view class="info-label">出版时间</view>
          <view class="info-value">{{ book.detail.publishTime }}</view>
        </view>
        <view class="info-row" v-if="book.detail.binding">
          <view class="info-label">装 帧</view>
          <view class="info-value">{{ book.detail.binding }}</view>
        </view>
        <view class="info-row" v-if="book.detail.price">
          <view class="info-label">定 价</view>
          <view class="info-value">{{ book.detail.price }}</view>
        </view>
        <view class="info-row" v-if="book.detail.dynasty">
          <view class="info-label">朝 代</view>
          <view class="info-value">{{ book.detail.dynasty }}</view>
        </view>
        <view class="info-row" v-if="book.detail.bookType">
          <view class="info-label">基本类型</view>
          <view class="info-value">{{ book.detail.bookType }}</view>
        </view>
        <view class="info-row" v-if="book.detail.value">
          <view class="info-label">价值影响</view>
          <view class="info-value">{{ book.detail.value }}</view>
        </view>
        <view class="info-row" v-for="(value, key) in otherDetails" :key="key">
          <view class="info-label">{{ formatLabel(key) }}</view>
          <view class="info-value">{{ value }}</view>
        </view>
      </view>
    </view>

    <!-- 音频播放器 -->
    <view class="audio-player">
      <view class="player-controls" @tap="togglePlayback">
        <text class="play-icon" v-if="!isPlaying">▶</text>
        <text class="pause-icon" v-else>❚❚</text>
      </view>
      <view class="player-info">
        <text>《{{ book.title }}》有声解读</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';

// 从路由参数获取书籍数据
const props = defineProps({
  bookId: {
    type: String,
    default: ''
  },
  category: {
    type: String,
    default: ''
  }
});

const url = $url;
const bookData = ref({});
const book = ref({ title: '', detail: {}, img: '' });
const audioContext = ref(null);
const isPlaying = ref(false);

onMounted(() => {
  // 从本地存储或页面参数获取数据
  const bookInfo = uni.getStorageSync('selectedBook');
  if (bookInfo) {
    book.value = JSON.parse(bookInfo);
  } else {
    // 使用API获取书籍数据
    fetchBookData();
  }

  // 初始化音频上下文
  initAudioContext();
});

onUnmounted(() => {
  // 清理音频资源
  if (audioContext.value) {
    audioContext.value.destroy();
  }
});

// 获取书籍数据
const fetchBookData = () => {
  if (props.category && props.bookId) {
    // 这里实际应该是API调用，这里模拟
    const booksData = {
      force: [
        {
          title: "梦溪笔谈",
          img: "0",
          content: '是百科全书式的著作，尤以其科学技术价值闻名于世。该书在国际亦受重视，英国科学史家李约瑟评价为"中国科学史上的里程碑"。',
          detail: {
            type: "重要古籍",
            author: "沈括",
            time: "11世纪，一说1086-1093",
            volume: "三十卷",
            pages: "342页",
            publishTime: "2003年3月",
            binding: "平装",
            price: "22元",
            dynasty: "北宋",
            bookType: "笔记体百科全书",
            value: "中国科学史上里程碑"
          }
        }
      ]
    };
    
    if (booksData[props.category]) {
      const foundBook = booksData[props.category].find(item => item.img === props.bookId);
      if (foundBook) {
        book.value = foundBook;
      }
    }
  }
};

// 初始化音频播放器
const initAudioContext = () => {
  try {
    // 创建音频上下文
    audioContext.value = uni.createInnerAudioContext();
    
    // 设置音频源https://mp-d7d620be-76ea-43bb-a05a-d38ceb13c655.cdn.bspapp.com/audio/book/gxxs.MP3
    const audioUrl = `https://mp-d7d620be-76ea-43bb-a05a-d38ceb13c655.cdn.bspapp.com/audio/book/${book.value.audio}.MP3`;
    
    // 直接设置音频源，不进行预检查
    audioContext.value.src = audioUrl;
    
    // 监听播放完成事件
    audioContext.value.onEnded(() => {
      isPlaying.value = false;
    });
    
    // 监听错误事件
    audioContext.value.onError((res) => {
      console.error('音频播放错误:', res.errMsg);
      isPlaying.value = false;
      
      // 根据错误类型显示不同提示
      if (res.errCode === 10002) {
        uni.showToast({
          title: '音频资源不存在',
          icon: 'none'
        });
      } else {
        uni.showToast({
          title: '播放出错，请稍后重试',
          icon: 'none'
        });
      }
    });
    
    // 监听加载成功事件
    audioContext.value.onCanplay(() => {
      console.log('音频加载成功，可以播放');
    });
    
  } catch (error) {
    console.error('初始化音频播放器失败:', error);
    uni.showToast({
      title: '音频播放器初始化失败',
      icon: 'none'
    });
  }
};

// 切换播放状态
const togglePlayback = () => {
  try {
    if (!audioContext.value || !audioContext.value.src) {
      uni.showToast({
        title: '暂无音频资源',
        icon: 'none'
      });
      return;
    }
    
    if (isPlaying.value) {
      audioContext.value.pause();
      isPlaying.value = false;
    } else {
      // 播放前添加加载提示
      uni.showLoading({
        title: '加载中...'
      });
      
      audioContext.value.play();
      
      // 监听一次播放开始事件
      audioContext.value.onPlay(() => {
        uni.hideLoading();
        isPlaying.value = true;
      });
      
      // 设置超时处理
      setTimeout(() => {
        if (!isPlaying.value) {
          uni.hideLoading();
          uni.showToast({
            title: '播放超时，请重试',
            icon: 'none'
          });
        }
      }, 5000);
    }
  } catch (error) {
    console.error('切换播放状态失败:', error);
    uni.hideLoading();
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

// 计算其他详情属性
const otherDetails = computed(() => {
  const excludeKeys = ['type', 'author', 'time', 'dynasty', 'volume', 'pages', 'publishTime', 'binding', 'price', 'bookType', 'value'];
  const result = {};
  
  if (book.value.detail) {
    Object.keys(book.value.detail).forEach(key => {
      if (!excludeKeys.includes(key)) {
        result[key] = book.value.detail[key];
      }
    });
  }
  
  return result;
});

// 格式化标签
const formatLabel = (key) => {
  const labels = {
    otherName: '别名',
    classification: '分类',
    theme: '主题',
    focus: '研究焦点',
    nameOrigin: '名称来源',
    status: '当前状态',
    publisher: '出版方',
    officialPost: '官职',
    content: '内容'
  };
  
  return labels[key] || key;
};
</script>

<style lang="scss" scoped>
.book-detail-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 40rpx;
  display: flex;
  flex-direction: column;
}

.book-cover-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}

.book-cover-circle {
  width: 300rpx;
  height: 300rpx;
  border-radius: 50%;
  overflow: hidden;
  background: #fff;
  border: 1px solid #e0e0e0;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
}

.book-cover {
  width: 100%;
  height: 100%;
}

.book-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.book-info-section {
  background:var(--td-bg-color-1);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 40rpx;
}

.info-table {
  width: 100%;
}

.info-row {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.info-label {
  width: 180rpx;
  color: #333;
  font-weight: bold;
}

.info-value {
  flex: 1;
  color: #666;
}

.audio-player {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  padding: 0 30rpx;
}

.player-controls {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: var(--td-brand-color, #4a90e2);
  color: #fff;
  font-size: 36rpx;
  margin-right: 20rpx;
}

.player-info {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}
</style> 